package br.com.nrti.still.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import android.os.Environment;

/**
 * Classe para manipulação dos arquivos de banco de dados SQLite (import/export)
 * A classe utiliza processamento em background (thread) para que um
 * progressDialog possa ser exibido
 * 
 * @author Nilson Rodrigo Carraro
 * 
 */

public class DbExportImport {

	/** Directory that files are to be read from and written to **/
	public static final String PACKAGE_NAME = "br.com.nrti.still";

	public static final String DB_NAME = "Still.db";
	public static final File OUT_DIRECTORY_DB = new File(Environment.getExternalStorageDirectory(), DB_NAME);
	public static final File IN_DIRECTORY_DB = new File(Environment.getDataDirectory() + "/data/" + PACKAGE_NAME
			+ "/databases/" + DB_NAME);

	/**
	 * Saves the application database to the export directory under MyDb.db
	 **/
	public static boolean exportDb() {

		if (!OUT_DIRECTORY_DB.getParentFile().exists())
			OUT_DIRECTORY_DB.getParentFile().mkdirs();

		try {
			OUT_DIRECTORY_DB.createNewFile();
			copyFile(IN_DIRECTORY_DB, OUT_DIRECTORY_DB);

			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * Replaces current database with the IMPORT_FILE if import database is
	 * valid and of the correct type
	 **/
	public static boolean importDb() {
		try {

			if (!OUT_DIRECTORY_DB.exists())
				return false;

			if (!IN_DIRECTORY_DB.getParentFile().exists())
				IN_DIRECTORY_DB.getParentFile().mkdirs();

			IN_DIRECTORY_DB.createNewFile();
			copyFile(OUT_DIRECTORY_DB, IN_DIRECTORY_DB);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	public static void copyFile(File src, File dst) throws IOException {
		FileChannel inChannel = new FileInputStream(src).getChannel();
		FileChannel outChannel = new FileOutputStream(dst).getChannel();
		try {
			inChannel.transferTo(0, inChannel.size(), outChannel);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (inChannel != null)
				inChannel.close();
			if (outChannel != null)
				outChannel.close();
		}
	}
}